import uuid

from fastapi import HTTPException
from sqlalchemy import Integer
from sqlalchemy.orm import Session

from api.model.llm_model import LLM
from api.utils.session import with_session
from api.vo.value.llm_value import LLMValue


@with_session
def add(session: Session, llm: LLM):
    session.add(llm)
    return llm

@with_session
def get_llm_by_model_type(session: Session):
    from sqlalchemy.sql.expression import cast
    llms = session.query(LLM).filter(LLM.status == "1").all()
    if not llms:
        return []
    list = [LLMValue(id=el.id, name=el.name, factory=el.factory, modelType=el.model_type) for el in llms]
    return list

@with_session
def exist_by_name(session: Session, name: str):
    llm = session.query(LLM).filter(LLM.name == name).first()
    if not llm:
        return False
    return True

@with_session
def delete_by_factory(session: Session, factory: str):
    llms = session.query(LLM).filter(LLM.factory == factory)
    if not llms:
        raise HTTPException(status_code=404, detail=f"{factory}不存在此类型的模型")
    for llm in llms:
        session.delete(llm)
    return llms

@with_session
def list(session: Session):
    llms = session.query(LLM).all()
    if not llms:
        return []
    list = [LLMValue(id=el.id, name=el.name, factory=el.factory, modelType=el.model_type, baseUrl=el.base_url,
                     apiKey=el.api_key, secretKey=el.secret_key, token=el.token) for el in llms]
    return list

@with_session
def delete(session: Session, id: str):
    llm = session.get(LLM, id)
    if not llm:
        raise HTTPException(status_code=404, detail=f"id={id}的模型不存在")
    session.delete(llm)
    return llm